<?php

namespace App\Repositories;

use App\Models\Bills;
use App\Models\SignOutTally;
use App\Models\StationBills;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class SettlementRepository extends BaseRepository
{
    const CHARGE = 0.10;

    public function model()
    {
        return StationBills::class;
    }

    /**
     * 获取快件结算账单列表
     * Date: 2018/05/10
     * @author Tenny
     * @param $service_id
     * @param $date
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getOrderBills($service_id, $date)
    {
        $base_bill = [
            "total_sign" => 0,
            "total_income" => 0,
            "charge" => 0.10,
            "total" => 0,
        ];
        $query = StationBills::query();
        if ($service_id !== false) {
            $query->where('station_bills.service_id', '=', $service_id);
        }
        if ($date !== false) {
            $query->where(DB::raw('month(station_bills.start_time)'), '=', date("m", strtotime($date)))
                ->where(DB::raw('year(station_bills.start_time)'), '=', date("Y", strtotime($date)));
        } else {
            $query->where(DB::raw('month(station_bills.start_time)'), '=', date("m", time()));
        }
        $stationBills = $query
            ->select(['station_bills.start_time', 'station_bills.end_time', 'station_bills.service_id', 'station_bills.total_sign', 'station_bills.charge', 'station_bills.total_income', 'station_bills.status', 'station_bills.number', 'service.designation as service_name'])
            ->leftJoin('service', 'station_bills.service_id', '=', 'service.id')
            ->orderBy('station_bills.service_id')
            ->orderBy('station_bills.start_time')
            ->with(['bills' => function ($query) {
                $query->with(['network']);
            }])
            ->get()
            ->toArray();
        //过滤非法数据
        if (is_array($stationBills) && count($stationBills) > 0) {
            foreach ($stationBills as $key => $stationBill) {
                if (is_array($stationBill['bills']) && count($stationBill['bills']) > 0) {
                    $stationBills[$key]['bill'] = [];
                    foreach ($stationBill['bills'] as $k => $bills) {
                        $stationBills[$key]['bills'][$k]['network_name'] = $bills['network']['designation'];
                        if (strtotime($stationBill['start_time']) <= strtotime($bills['date']) && strtotime($stationBill['end_time']) >= strtotime($bills['date'])) {
                            if (array_key_exists($bills['date'], $stationBills[$key]['bill'])) {
                                $stationBills[$key]['bill'][$bills['date']]['total_sign'] = round($stationBills[$key]['bill'][$bills['date']]['total_sign'] + $bills['total_sign'], 2);
                                $stationBills[$key]['bill'][$bills['date']]['total_income'] = round($stationBills[$key]['bill'][$bills['date']]['total_income'] + $bills['total_income'], 2);
                                $charge = round($bills['total_sign'] * self::CHARGE, 2);
                                $total = round($bills['total_income'] - $charge, 2);
                                $stationBills[$key]['bill'][$bills['date']]['total'] = round($stationBills[$key]['bill'][$bills['date']]['total'] + $total, 2);
                            } else {
                                unset($bills['id'], $bills['service_id'], $bills['network_id'], $bills['created_at'], $bills['updated_at'], $bills['network']);
                                $bills['charge'] = self::CHARGE;
                                $charge = round($bills['total_sign'] * self::CHARGE, 2);
                                $bills['total'] = round($bills['total_income'] - $charge, 2);
                                $stationBills[$key]['bill'][$bills['date']] = $bills;
                            }
                        } else {
                            unset($stationBills[$key]['bills'][$k]);
                        }
                        unset($stationBills[$key]['bills'][$k]['network']);
                    }
                    //根据日期生成基础数据
                    $start_time = $stationBill['start_time'];
                    $end_time = $stationBill['end_time'];
                    for ($i = 1; $i <= 15; $i++) {
                        $date = date("Y-m-d", strtotime("$start_time + " . $i . " days"));
                        if (strtotime($date) > strtotime($end_time)) {
                            break;
                        }
                        if (!array_key_exists($date, $stationBills[$key]['bill'])) {
                            $stationBills[$key]['bill'][$date] = $base_bill;
                            $stationBills[$key]['bill'][$date]['date'] = $date;
                        }
                    }
                    //序列化数组
                    if (is_array($stationBills[$key]['bill']) && count($stationBills[$key]['bill']) > 0) {
                        ksort($stationBills[$key]['bill']);
                        $stationBills[$key]['bill'] = array_values($stationBills[$key]['bill']);
                    }
                }
                unset($stationBills[$key]['bills']);
            }
        }
        return $stationBills;
    }

    /**
     * 获取快件结算详情
     * Date: 2018/05/10
     * @author Tenny
     * @param $service_id
     * @param $date
     * @param $limit
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getOrderBillDetails($service_id, $date, $limit)
    {
        $query = Bills::query();
        if ($service_id !== false) {
            $query->where('bills.service_id', '=', $service_id);
        }
        if ($date !== false) {
            $query->where('bills.date', '=', date("Y-m-d", strtotime($date)));
        } else {
            $query->where('bills.date', '=', date("Y-m-d", time()));
        }
        $bills = $query
            ->select(['bills.*', 'network.designation as network_name', 'n.unit_price'])
            ->leftJoin('network', 'bills.network_id', '=', 'network.id')
            ->leftJoin('network_express as n', function ($query) {
                $query->on('n.service_id', '=', 'bills.service_id')
                    ->on('n.network_id', '=', 'bills.network_id');
            })
            ->orderBy('bills.service_id')
            ->paginate($limit);
        return $bills;
    }

    /**
     * 获取网点账单
     * Date: 2018/05/10
     * @author Tenny
     * @param $network_id
     * @param $date
     * @param $limit
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getNetworkBills($network_id, $date, $limit)
    {
        $query = Bills::query();
        if ($network_id !== false) {
            $query->where('bills.network_id', '=', $network_id);
        }
        if ($date !== false) {
            $query->where('bills.date', '=', date("Y-m-d", strtotime($date)));
        } else {
            $query->where('bills.date', '=', date("Y-m-d", time()));
        }
        $bills = $query
            ->select(['bills.*', 'service.designation as service_name', 'n.unit_price'])
            ->leftJoin('service', 'bills.service_id', '=', 'service.id')
            ->leftJoin('network_express as n', function ($query) {
                $query->on('n.service_id', '=', 'bills.service_id')
                    ->on('n.network_id', '=', 'bills.network_id');
            })
            ->orderBy('bills.service_id')
            ->paginate($limit);
        return $bills;
    }

    /**
     * 获取网点账单详情
     * Date: 2018/05/10
     * @author Tenny
     * @param $network_id
     * @param $date
     * @param $limit
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getNetworkBillDetails($network_id, $service_id, $date, $limit)
    {
        $query = SignOutTally::query();
        if ($network_id !== false) {
            $query->where('sign_out_tally.network_id', '=', $network_id);
        }
        if ($service_id !== false) {
            $query->where('sign_out_tally.service_id', '=', $service_id);
        }
        if ($date !== false) {
            $time = [
                date("Y-m-d 00:00:00", strtotime($date)),
                date("Y-m-d 23:59:59", strtotime($date)),
            ];
            $query->whereBetween('sign_out_tally.created_at', $time);
        } else {
            $time = [
                date("Y-m-d 00:00:00", time()),
                date("Y-m-d 23:59:59", time()),
            ];
            $query->whereBetween('sign_out_tally.created_at', $time);
        }
        $bills = $query
            ->select(['sign_out_tally.*', 'order.order_id as order_number', 'order.single_number', 'order.to_mobile', 'order.created_at as order_created_at'])
            ->leftJoin('order', 'order.id', '=', 'sign_out_tally.order_id')
            ->where('sign_out_tally.status', '=', 0)
            ->orderBy('sign_out_tally.created_at')
            ->paginate($limit);
        return $bills;
    }

    protected function serialization(array $attributes)
    {
        // TODO: Implement serialization() method.
    }
}